package com.itheima.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.goods.mapper.CategoryMapper;
import com.itheima.goods.pojo.Category;
import com.itheima.goods.service.CategoryService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {
    @Override
    public Result findAll() {
        List<Category> list = this.list();
        return new Result(true,StatusCode.OK,null,list);
    }

    @Override
    public Result findByParentId(Integer parentId) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Category::getParentId, parentId);
        List<Category> list = this.list(wrapper);
        return new Result(true, StatusCode.OK, "请求完成",list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addCategory(Category category) {

        boolean save = this.save(category);
        if (!save) {
            return new Result(false, StatusCode.ERROR, "添加失败", category);
        }
        return new Result(true, StatusCode.OK, "添加成功", category);
    }

    @Override
        public PageResult<Category> findPage(Integer currentPage, Integer pageSize, Integer queryString) {
        Page<Category> categoryPage = new Page<>(currentPage, pageSize);

        IPage<Category> categoryIPage = this.page(categoryPage, new QueryWrapper<Category>());
        return new PageResult<>(categoryIPage.getTotal(),categoryIPage.getRecords());
    }

    @Override
    public Result findById(Integer id) {

        Category findId = this.getOne(new QueryWrapper<Category>().eq("id", id));

        return new Result(true,StatusCode.OK,"查找成功",findId);
    }

    @Override
    public Result updateCategory(Integer id ,Category category) {

            this.update(category, new UpdateWrapper<Category>().eq("id", id));
            return new Result(true, StatusCode.OK, null, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteCategory(Integer id) {


        boolean deleteResult = this.removeById(id);

        return new Result(deleteResult, StatusCode.OK, null);
    }
}
